package com.lznAdmin.security.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.lznAdmin.base.common.util.JwtUtil;
import com.lznAdmin.base.common.util.RedisUtil;
import com.lznAdmin.base.lznAdminResult;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @program: lzn-manage-parent
 * @description: 注销登录相关
 * @author: lzn
 * @create: 2021-10-12 23:40
 **/
@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    @Qualifier("handlerExceptionResolver")
    HandlerExceptionResolver resolver;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }

        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();


        String jwt = request.getHeader(jwtUtil.getHeader());
        if (StrUtil.isEmpty(jwt)) {
            JwtException tokenOver = new JwtException("token异常");
            resolver.resolveException(request, response, null, tokenOver);
            return;
        }
        // 清除Redis登录名单
        Claims claimByToken = jwtUtil.getClaimByToken(jwt);
        if (claimByToken != null) {
            logger.info("清除Redis登录名单: {}", claimByToken.getSubject());
            jwtUtil.delLoginList(claimByToken.getSubject());
        }

        response.setHeader(jwtUtil.getHeader(), "");

        lznAdminResult result = lznAdminResult.ok("");

        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }

}
